<template>
  <div>
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :before-upload="beforeAvatarUpload"
      :http-request="upload"
    >
      <img v-if="value" :src="value" class="avatar" />
      <i v-else class="el-icon-plus avatar-uploader-icon" />
      <el-progress v-if="show" :percentage="percentage" class="progress" />
    </el-upload>
  </div>
</template>

<script>
const COS = require('cos-js-sdk-v5')
// 填写自己腾讯云cos中的key和id (密钥)
const cos = new COS({
  SecretId: 'AKIDmRuQq691hEajdIisoX4LNDn7AxVnqjRw', // 身份识别ID
  SecretKey: 'MTLzOXS9dIl03uXu41jBNK2iFZfW8Whh' // 身份秘钥
})
export default {
  props: {
    value: { type: String, default: '' }
  },
  data() {
    return {
      imageUrl: '',
      percentage: 0,
      show: false
    }
  },
  methods: {
    upload(res) {
      if (res.file) {
        this.show = true
        // 执行上传操作
        cos.putObject(
          {
            Bucket: 'ssk-hr-1307143937' /* 存储桶 */,
            Region: 'ap-beijing' /* 存储桶所在地域，必须字段 */,
            Key: res.file.name /* 文件名 */,
            StorageClass: 'STANDARD', // 上传模式, 标准模式
            Body: res.file, // 上传文件对象
            onProgress: progressData => {
              console.log(JSON.stringify(progressData))
              this.percentage = progressData.percent * 100
            }
          },
          (err, data) => {
            this.show = false
            console.log(err || data)
            // 上传成功之后
            if (data.statusCode === 200) {
              this.$emit('input', `https://${data.Location}`)
              //  this.imageUrl = `https://${data.Location}`
            }
          }
        )
      }
    },

    beforeAvatarUpload() {
      return true
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
